package com.nl.lib_project.view.radar

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import java.lang.ref.WeakReference

/**
 * Created by chqiu on 2016/9/5.
 */
class AnimeUtil(view: RadarView) {
    private val mWeakRadarView: WeakReference<RadarView> = WeakReference(view)
    private val mAnime: HashMap<RadarData, ValueAnimator> = HashMap()
    fun animeValue(type: AnimeType?, duration: Int, data: RadarData) {
        when (type) {
            AnimeType.ZOOM -> startZoomAnime(duration, data)
        }
    }

    val isPlaying: Boolean
        get() {
            var isPlaying = false
            for (anime in mAnime.values) {
                isPlaying = anime.isStarted
                if (isPlaying) {
                    break
                }
            }
            return isPlaying
        }

    fun isPlaying(data: RadarData): Boolean {
        val anime = mAnime[data]
        return anime != null && anime.isStarted
    }

    private fun startZoomAnime(duration: Int, data: RadarData) {
        val anime = ValueAnimator.ofFloat(0f, 1f)
        val values = data.value
        val values2: List<Float?> = ArrayList(values)
        anime.addUpdateListener { animation ->
            val view = mWeakRadarView.get()
            if (view == null) {
                anime.end()
            } else {
                val percent = animation.animatedValue.toString().toFloat()
                for (i in values.indices) {
                    values[i] = values2[i]!! * percent
                }
                view.invalidate()
            }
        }
        anime.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                mAnime.remove(data)
            }
        })
        anime.setDuration(duration.toLong()).start()
        mAnime[data] = anime
    }

    enum class AnimeType {
        ZOOM, ROTATE
    }

}